package com.example.logindemo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.example.logindemo.config.JwtAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
                .antMatchers("/login", "/register", "/css/**", "/js/**", "/images/**").permitAll()
                // 用户自己的跑单列表 - 需要认证（放在/api/**之前）
                .antMatchers("/api/my/orders").authenticated()
                // 用户查看单个跑单详情 - 需要认证
                .antMatchers("/orders/*").authenticated()
                // 允许API路径 - 需要认证
                .antMatchers("/api/**").authenticated()
                // 评价相关 - 需要认证
                .antMatchers("/reviews").authenticated()
                // 管理面板 - 需要ADMIN角色
                .antMatchers("/dashboard**").hasRole("ADMIN")
                // 用户管理 - 需要ADMIN角色
                .antMatchers("/admin/**").hasRole("ADMIN")
                // 订单管理（管理功能）- 需要ADMIN或MODERATOR角色
                .antMatchers("/orders/manage/**").hasAnyRole("ADMIN", "MODERATOR")
                // 评价管理 - 需要ADMIN或MODERATOR角色
                .antMatchers("/reviews/manage/**").hasAnyRole("ADMIN", "MODERATOR")
                // 其他所有请求都需要认证
                .anyRequest().authenticated()
            .and()
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}